<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>创建商品 - 管理员中心</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#165DFF',
                        secondary: '#36CFC9',
                        neutral: '#86909C',
                        light: '#F2F3F5',
                        dark: '#1D2129'
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .form-input {
                @apply w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary/50 transition-all;
            }
            .form-label {
                @apply block text-sm font-medium text-gray-700 mb-1;
            }
            .btn-primary {
                @apply bg-primary text-white px-6 py-2 rounded-md hover:bg-primary/90 transition-all hover:shadow-md;
            }
            .btn-secondary {
                @apply bg-gray-200 text-gray-700 px-6 py-2 rounded-md hover:bg-gray-300 transition-all;
            }
            .error-message {
                @apply text-red-500 text-sm mt-1 hidden;
            }
            .error-message.show {
                @apply block;
            }
        }
    </style>
</head>
<body class="bg-gray-50 text-dark font-sans">
    <!-- 导航栏 -->
    <header id="navbar" class="fixed top-0 left-0 right-0 bg-white shadow-sm z-50">
        <div class="container mx-auto px-4">
            <div class="flex items-center justify-between h-16">
                <a href="../index.html" class="flex items-center space-x-2">
                    <span class="logo text-2xl font-bold text-blue-600">蓝猫</span>
                </a>
                
                <nav class="hidden md:flex items-center space-x-8">
                    <a href="../index.html" class="font-medium hover:text-primary transition-colors">首页</a>
                    <a href="products.html" class="font-medium text-primary border-b-2 border-primary pb-1">商品管理</a>
                    <a href="#" class="font-medium hover:text-primary transition-colors">订单管理</a>
                </nav>
                
                <div class="flex items-center space-x-4">  
                    <div id="admin-links" class="hidden items-center space-x-4">
                        <a href="products.html" class="text-sm font-medium hover:text-primary transition-colors">商品列表</a>
                        <a href="create-product.html" class="text-sm font-medium text-primary transition-colors">添加商品</a>
                    </div>
                    
                    <div id="auth-links" class="flex items-center space-x-4">
                        <a href="../login.html" class="p-2 hover:text-primary transition-colors">
                            <i class="fa fa-sign-in text-xl"></i>
                        </a>
                    </div>
                    
                    <div id="user-info" class="hidden items-center space-x-4">
                        <span id="username-display" class="text-sm font-medium"></span>
                        <button id="logoutBtn" class="text-sm text-gray-500 hover:text-primary transition-colors">退出</button>
                    </div>

                    <!-- 移动端菜单按钮 -->
                    <button id="mobileMenuBtn" class="md:hidden p-2 hover:text-primary transition-colors">
                        <i class="fa fa-bars text-xl"></i>
                    </button>                       
                </div>
            </div>
        </div>
    </header>

    <main class="pt-24 pb-16">
        <div class="container mx-auto px-4 max-w-3xl">
            <div class="bg-white rounded-lg shadow-sm p-6 md:p-8 mb-8">
                <h1 class="text-2xl font-bold mb-6">添加新商品</h1>
                
                <!-- 成功提示 -->
                <div id="successAlert" class="bg-green-50 border border-green-200 text-green-700 px-4 py-3 rounded mb-6 hidden">
                    <strong class="font-bold">成功!</strong>
                    <span class="block sm:inline" id="successMessage">商品创建成功</span>
                </div>
                
                <form id="createProductForm" class="space-y-6">
                    <!-- 商品基本信息 -->
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <div>
                            <label for="name" class="form-label">商品名称 <span class="text-red-500">*</span></label>
                            <input type="text" id="name" name="name" class="form-input" required>
                            <div id="nameError" class="error-message">请输入商品名称</div>
                        </div>
                        
                        <div>
                            <label for="category" class="form-label">商品分类 <span class="text-red-500">*</span></label>
                            <select id="category" name="category" class="form-input" required>
                                <option value="">请选择分类</option>
                                <option value="电子产品">电子产品</option>
                                <option value="服装鞋帽">服装鞋帽</option>
                                <option value="家居用品">家居用品</option>
                                <option value="食品饮料">食品饮料</option>
                                <option value="图书音像">图书音像</option>
                            </select>
                            <div id="categoryError" class="error-message">请选择商品分类</div>
                        </div>
                    </div>
                    
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-12">
                        <div>
                            <label for="price" class="form-label">商品价格 (元) <span class="text-red-500">*</span></label>
                            <input type="number" id="price" name="price" min="0.01" step="0.01" class="form-input" required>
                            <div id="priceError" class="error-message">请输入有效的价格（大于0）</div>
                        </div>
                        
                        <div>
                            <label for="stock" class="form-label">初始库存 <span class="text-red-500">*</span></label>
                            <input type="number" id="stock" name="stock" min="0" step="1" class="form-input" required>
                            <div id="stockError" class="error-message">请输入有效的库存数量（大于等于0）</div>
                        </div>
                    </div>
                    
                    <div>
                        <label for="description" class="form-label">商品描述</label>
                        <textarea id="description" name="description" rows="4" class="form-input" placeholder="请输入商品详细描述..."></textarea>
                    </div>
                    
                    <div>
                        <label for="imageUrl" class="form-label">商品图片 URL</label>
                        <input type="url" id="imageUrl" name="image_url" class="form-input" placeholder="https://example.com/image.jpg">
                        <div id="imageUrlError" class="error-message">请输入有效的图片URL</div>
                    </div>

                    <!-- 商品图片上传 -->
                    <div>
                        <label class="form-label">商品图片 <span class="text-red-500">*</span></label>
                        <div class="mt-1 flex justify-center px-6 pt-5 pb-6 border-2 border-gray-300 border-dashed rounded-md">
                            <div class="space-y-1 text-center">
                                <i class="fa fa-cloud-upload text-3xl text-gray-400"></i>
                                <div class="flex text-sm text-gray-600">
                                    <label for="file-upload" class="relative cursor-pointer bg-white rounded-md font-medium text-primary hover:text-primary/80">
                                        <span>上传图片</span>
                                        <input id="file-upload" name="image" type="file" accept="image/*" class="sr-only">
                                    </label>
                                    <p class="pl-1">或拖放文件</p>
                                </div>
                                <p class="text-xs text-gray-500">支持 PNG, JPG, GIF 格式</p>
                            </div>
                        </div>
                        <div class="error-message" id="imageError">请上传商品图片</div>
                        <!-- 预览图 -->
                        <div id="imagePreviewContainer" class="mt-4 hidden">
                            <img id="imagePreview" src="" alt="预览图" class="max-h-64 object-contain rounded-md border">
                        </div>
                    </div>             
                    <!-- 商品评分 -->
                    <div>
                        <label class="form-label">初始评分</label>
                        <div class="flex items-center mt-1">
                            <div class="flex text-2xl text-gray-300">
                                <i class="fa fa-star rating-star cursor-pointer hover:text-yellow-400 transition-colors" data-rating="1"></i>
                                <i class="fa fa-star rating-star cursor-pointer hover:text-yellow-400 transition-colors" data-rating="2"></i>
                                <i class="fa fa-star rating-star cursor-pointer hover:text-yellow-400 transition-colors" data-rating="3"></i>
                                <i class="fa fa-star rating-star cursor-pointer hover:text-yellow-400 transition-colors" data-rating="4"></i>
                                <i class="fa fa-star rating-star cursor-pointer hover:text-yellow-400 transition-colors" data-rating="5"></i>
                            </div>
                            <input type="hidden" id="productRating" name="rating" value="0">
                        </div>
                    </div>
                    
                    <!-- 商品评价数 -->
                    <div>
                        <label for="productReviews" class="form-label">初始评价数量</label>
                        <input type="number" id="productReviews" name="reviews" min="0" value="0" class="form-input">
                    </div>
                                        
                    <!-- 表单操作按钮 -->
                    <div class="pt-8 flex justify-end space-x-8">
                        <a href="products.html" class="btn-secondary">取消</a>
                        <button type="submit" class="btn-primary" id="submitBtn">
                            <i class="fa fa-save mr-1"></i> 创建商品
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </main>

    <!-- 加载遮罩 -->
    <div id="loadingOverlay" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden">
        <div class="bg-white p-6 rounded-lg shadow-lg flex items-center">
            <div class="animate-spin rounded-full h-8 w-8 border-t-2 border-b-2 border-primary mr-4"></div>
            <p>处理中，请稍候...</p>
        </div>
    </div>

    <script>
        // 全局变量
        let accessToken = localStorage.getItem('access_token');
        let currentUser = null;

        // DOM元素
        const createForm = document.getElementById('createProductForm');
        const fileUpload = document.getElementById('file-upload');
        const imagePreview = document.getElementById('imagePreview');
        const imagePreviewContainer = document.getElementById('imagePreviewContainer');
        const submitBtn = document.getElementById('submitBtn');
        const loadingOverlay = document.getElementById('loadingOverlay');
        const successAlert = document.getElementById('successAlert');
        const successMessage = document.getElementById('successMessage');
        const ratingStars = document.querySelectorAll('.rating-star');
        const productRating = document.getElementById('productRating');

        // 错误提示元素
        const errorElements = {
            name: document.getElementById('nameError'),
            category: document.getElementById('categoryError'),
            price: document.getElementById('priceError'),
            stock: document.getElementById('stockError'),
            imageUrl: document.getElementById('imageUrlError')
        };

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', () => {
            // 检查管理员权限
            checkAdminAuth();
            
            // 设置表单提交事件
            createForm.addEventListener('submit', handleFormSubmit);
            // 图片上传预览
            fileUpload.addEventListener('change', handleImageUpload);            
            // 设置登出事件
            document.getElementById('logoutBtn').addEventListener('click', logout);
            // 评分星星点击事件
            ratingStars.forEach(star => {
                star.addEventListener('click', () => {
                    selectedRating = parseInt(star.dataset.rating);
                    updateRatingStars();
                    productRating.value = selectedRating;
                });
            });            
            // 为输入框添加实时验证
            setupRealTimeValidation();
        });

        // 设置实时验证
        function setupRealTimeValidation() {
            // 商品名称验证
            document.getElementById('name').addEventListener('blur', (e) => {
                if (!e.target.value.trim()) {
                    showError('name', '请输入商品名称');
                } else {
                    hideError('name');
                }
            });
            
            // 价格验证
            document.getElementById('price').addEventListener('blur', (e) => {
                const value = parseFloat(e.target.value);
                if (isNaN(value) || value <= 0) {
                    showError('price', '请输入有效的价格（大于0）');
                } else {
                    hideError('price');
                }
            });
            
            // 库存验证
            document.getElementById('stock').addEventListener('blur', (e) => {
                const value = parseInt(e.target.value, 10);
                if (isNaN(value) || value < 0) {
                    showError('stock', '请输入有效的库存数量（大于等于0）');
                } else {
                    hideError('stock');
                }
            });
            
            // 图片URL验证（如果填写）
            document.getElementById('imageUrl').addEventListener('blur', (e) => {
                const value = e.target.value.trim();
                if (value && !isValidUrl(value)) {
                    showError('imageUrl', '请输入有效的图片URL');
                } else {
                    hideError('imageUrl');
                }
            });
        }

        // 检查管理员权限
        async function checkAdminAuth() {
            if (!accessToken) {
                // 没有令牌，重定向到登录页
                redirectToLogin('请先登录管理员账号');
                return;
            }

            try {
                // 验证用户身份并获取用户信息
                const response = await fetch('http://192.168.10.124:8000/auth/user/', {
                    headers: { 'Authorization': `Bearer ${accessToken}` }
                });

                if (response.ok) {
                    currentUser = await response.json();
                    document.getElementById('username-display').textContent = currentUser.username;
                    updateAuthUI(true);
                } else {
                    throw new Error('验证失败');
                }
            } catch (error) {
                console.error('权限验证失败:', error);
                localStorage.removeItem('access_token');
                redirectToLogin('登录已过期，请重新登录');
            }
        }

        // 更新认证相关UI
        function updateAuthUI(isAuthenticated) {
            if (isAuthenticated) {
                document.getElementById('auth-links').classList.add('hidden');
                document.getElementById('user-info').classList.remove('hidden');
                document.getElementById('admin-links').classList.remove('hidden');
            } else {
                document.getElementById('auth-links').classList.remove('hidden');
                document.getElementById('user-info').classList.add('hidden');
                document.getElementById('admin-links').classList.add('hidden');
            }
        }

        // 重定向到登录页
        function redirectToLogin(message) {
            // 显示提示消息
            const tempToast = document.createElement('div');
            tempToast.className = 'fixed top-4 left-1/2 transform -translate-x-1/2 bg-red-500 text-white px-4 py-2 rounded-md z-50';
            tempToast.textContent = message;
            document.body.appendChild(tempToast);
            
            // 延迟重定向
            setTimeout(() => {
                window.location.href = '../login.html';
            }, 1500);
        }

        // 表单验证
        function validateForm(formData) {
            let isValid = true;
            clearAllErrors();
            
            // 验证商品名称
            if (!formData.name.trim()) {
                showError('name', '请输入商品名称');
                isValid = false;
            }
            
            // 验证分类
            if (!formData.category) {
                showError('category', '请选择商品分类');
                isValid = false;
            }
            
            // 验证价格
            if (isNaN(formData.price) || formData.price <= 0) {
                showError('price', '请输入有效的价格（大于0）');
                isValid = false;
            }
            
            // 验证库存
            if (isNaN(formData.stock) || formData.stock < 0) {
                showError('stock', '请输入有效的库存数量（大于等于0）');
                isValid = false;
            }
            
            // 验证图片URL（如果填写）
            if (formData.image_url && formData.image_url.trim() && !isValidUrl(formData.image_url)) {
                showError('imageUrl', '请输入有效的图片URL');
                isValid = false;
            }
            
            return isValid;
        }

        // 处理图片上传预览
        function handleImageUpload() {
            if (fileUpload.files && fileUpload.files[0]) {
                const reader = new FileReader();
                
                reader.onload = function(e) {
                    imagePreview.src = e.target.result;
                    imagePreviewContainer.classList.remove('hidden');
                    
                    // 隐藏图片错误提示
                    document.getElementById('imageError').classList.add('hidden');
                }
                
                reader.readAsDataURL(fileUpload.files[0]);
            }
        }

        // 更新评分星星显示
        function updateRatingStars() {
            ratingStars.forEach(star => {
                const starRating = parseInt(star.dataset.rating);
                if (starRating <= selectedRating) {
                    star.classList.remove('text-gray-300');
                    star.classList.add('text-yellow-400');
                } else {
                    star.classList.remove('text-yellow-400');
                    star.classList.add('text-gray-300');
                }
            });
        }

        // 显示错误信息
        function showError(field, message) {
            if (errorElements[field]) {
                errorElements[field].textContent = message;
                errorElements[field].classList.add('show');
            }
        }

        // 隐藏错误信息
        function hideError(field) {
            if (errorElements[field]) {
                errorElements[field].classList.remove('show');
            }
        }

        // 清除所有错误信息
        function clearAllErrors() {
            Object.keys(errorElements).forEach(field => {
                hideError(field);
            });
        }

        // 验证URL格式
        function isValidUrl(url) {
            try {
                new URL(url);
                return true;
            } catch (e) {
                return false;
            }
        }
        // 临时替换 showSuccess 函数，排除 DOM 元素问题
        function showSuccess(message) {
            alert(message); // 用原生 alert 避免 DOM 依赖
            createForm.reset();
        }
        // 处理表单提交（修复错误处理部分）
        async function handleFormSubmit(e) {
            e.preventDefault();
            
            // 收集表单数据（不变）
            const formData = {
                name: document.getElementById('name').value.trim(),
                category: document.getElementById('category').value,
                price: parseFloat(document.getElementById('price').value),
                stock: parseInt(document.getElementById('stock').value, 10),
                description: document.getElementById('description').value.trim(),
                rating: parseFloat(productRating.value) || 0,
                reviews: parseInt(document.getElementById('productReviews').value, 10) || 0,
                image_url: document.getElementById('imageUrl').value.trim() || null
            };
            
            // 表单验证（不变）
            if (!validateForm(formData)) {
                return;
            }
            
            try {
                // 显示加载状态
                showLoading();
                
                // 发送创建商品请求
                const response = await fetch('http://192.168.10.124:8000/products/', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${accessToken}`
                    },
                    body: JSON.stringify(formData)
                });           
                // 隐藏加载状态
                hideLoading();

                if (response.ok) {
                    // 商品创建成功（不变）
                    const newProduct = await response.json();
                    showSuccess(`商品 "${newProduct.name}" 创建成功`);                    
                } else {
                    // 修复错误处理逻辑
                    const errorData = await response.json().catch(() => ({}));
                    let errorMessage = '创建商品失败，请重试';
                    
                    // 解析错误信息（处理对象或数组形式的错误）
                    if (typeof errorData.detail === 'string') {
                        // 如果错误是字符串，直接使用
                        errorMessage = errorData.detail;
                    } else if (Array.isArray(errorData.detail)) {
                        // 如果错误是数组，拼接成字符串
                        errorMessage = errorData.detail.map(item => {
                            // 处理可能的字段错误（如 {"loc": ["name"], "msg": "不能为空"}）
                            if (item.loc && item.msg) {
                                const field = item.loc[item.loc.length - 1];
                                return `${getFieldName(field)}: ${item.msg}`;
                            }
                            return item;
                        }).join('，');
                    } else if (typeof errorData.detail === 'object') {
                        // 如果错误是对象，提取所有值并拼接
                        errorMessage = Object.values(errorData.detail).join('，');
                    }
                    
                    // 显示错误信息
                    showError('name', errorMessage);
                }
            } catch (error) {
                console.error('创建商品失败:', error);
                hideLoading();
                // 显示友好的错误信息，而不是直接显示错误对象
                showError('name', '网络错误，请检查连接后重试');
            }
        }

        // 辅助函数：将字段名转换为中文显示
        function getFieldName(field) {
            const fieldMap = {
                'name': '商品名称',
                'category': '商品分类',
                'price': '商品价格',
                'stock': '库存数量',
                'image_url': '商品图片URL'
            };
            return fieldMap[field] || field;
        }

        // 其他函数不变...
        function showError(field, message) {
            if (errorElements[field]) {
                errorElements[field].textContent = message;
                errorElements[field].classList.add('show');
            }
        }

        function showLoading() {
            loadingOverlay.classList.remove('hidden');
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<i class="fa fa-spinner fa-spin mr-1"></i> 处理中...';
        }

        function hideLoading() {
            loadingOverlay.classList.add('hidden');
            submitBtn.disabled = false;
            submitBtn.innerHTML = '<i class="fa fa-save mr-1"></i> 创建商品';
        }

        // 登出功能
        function logout() {
            localStorage.removeItem('access_token');
            accessToken = null;
            currentUser = null;
            updateAuthUI(false);
            
            // 显示提示并跳转
            const tempToast = document.createElement('div');
            tempToast.className = 'fixed top-4 left-1/2 transform -translate-x-1/2 bg-green-500 text-white px-4 py-2 rounded-md z-50';
            tempToast.textContent = '已成功退出登录';
            document.body.appendChild(tempToast);
            
            setTimeout(() => {
                window.location.href = '../index.html';
            }, 1000);
        }
    </script>
</body>
</html>
